<?php
/**
 * Created by PhpStorm.
 * User: wuchao
 * Date: 2020/4/15
 * Time: 10:48
 */

namespace app\api\model;

use \Exception as E;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use \think\response\Json;

class GoodsModel
{
    private static $_table = 'goods'; // banner表
    private static $goods_reply = 'goods_reply'; // 商品评论表
    private static $goods_log = 'goods_log'; // 商品日志表
//    private static $_dirver_routeTable = 'dirver_route'; // 司机路由表

    /**获取是否新品商品
     * @param array $input
     * @return array
     */
    public static function GetGoodsNew($input)
    {
        try {
            $map = [
                ['a.admin_id', '=', $input['admin_id']],
                ['a.is_new', '=', 1],
                ['a.status', '=', 1],
            ];
            $fields = 'a.id,a.name,a.info,a.image,a.price,a.ot_price,a.sales,a.stock,b.name as unit_name';
            $table = Db::table(self::$_table)->alias('a')
                ->join('goods_unit b', 'a.unit_id = b.id')
                ->field($fields)->limit(10);
            if ($input['center_ids']) {
                $center_ids = explode(',', $input['center_ids']);
                $map[] = ['a.center_id', 'in', $center_ids];
                $data = $table->where($map)->select()->toArray();
            } else {
                $data = $table->where($map)->select()->toArray();
            }
            return $data;
        } catch (DataNotFoundException $e) {
            return [];
        } catch (ModelNotFoundException $e) {
            return [];
        } catch (DbException $e) {
            return [];
        } catch (E $e) {
            return [];
        }
    }

    /**获取是否热品商品
     * @param array $input
     * @return array
     */
    public static function GetGoodsHot($input)
    {
        try {
            $map = [
                ['a.admin_id', '=', $input['admin_id']],
                ['a.is_hot', '=', 1],
                ['a.status', '=', 1],
            ];
            $fields = 'a.id,a.name,a.info,a.image,a.price,a.ot_price,a.sales,a.stock,b.name as unit_name';
            $table = Db::table(self::$_table)->alias('a')
                ->join('goods_unit b', 'a.unit_id = b.id')
                ->field($fields)->limit(10);
            if ($input['center_ids']) {
                $center_ids = explode(',', $input['center_ids']);
                $map[] = ['a.center_id', 'in', $center_ids];
                $data = $table->where($map)->select()->toArray();
            } else {
                $data = $table->where($map)->select()->toArray();
            }
            return $data;
        } catch (DataNotFoundException $e) {
            return [];
        } catch (ModelNotFoundException $e) {
            return [];
        } catch (DbException $e) {
            return [];
        } catch (E $e) {
            return [];
        }
    }

    /**获取是否活动中商品
     * @param array $input
     * @return array
     */
    public static function GetGoodsActivity($input)
    {
        try {
            $map = [
                ['a.admin_id', '=', $input['admin_id']],
                ['a.is_activity', '=', 1],
                ['a.status', '=', 1],
            ];
            $fields = 'a.id,a.name,a.info,a.image,a.price,a.ot_price,a.act_price,a.sales,a.stock,b.name as unit_name';
            $table = Db::table(self::$_table)->alias('a')
                ->join('goods_unit b', 'a.unit_id = b.id')
                ->field($fields)->limit(10);
            if ($input['center_ids']) {
                $center_ids = explode(',', $input['center_ids']);
                $map[] = ['a.center_id', 'in', $center_ids];
                $data = $table->where($map)->select()->toArray();
            } else {
                $data = $table->where($map)->select()->toArray();
            }
            return $data;
        } catch (DataNotFoundException $e) {
            return [];
        } catch (ModelNotFoundException $e) {
            return [];
        } catch (DbException $e) {
            return [];
        } catch (E $e) {
            return [];
        }
    }
    /**模糊搜索商品
     * @param $input
     * @return Json
     */
    public static function search($input)
    {
        $center_ids = explode(',', $input['center_ids']);
        $field = 'a.id,a.name,a.image,a.cate_id,a.price,a.ot_price,a.act_price,a.is_activity,a.is_hot,a.stock,a.sales,b.name as unit_name';
        $table = Db::table(self::$_table)->alias('a')->join('goods_unit b', 'a.unit_id = b.id');
        $map[] = ['a.status', '=', 1];
        $map[] = ['a.center_id', 'in', $center_ids];
        $map[] = ['a.name', 'like', "%{$input['text']}%"];
        if ($input['is_new'] === '1') $map[] = ['a.is_new', '=', 1];
        if ($input['is_hot'] === '1') $map[] = ['a.is_hot', '=', 1];
        if ($input['is_activity'] === '1') $map[] = ['a.is_activity', '=', 1];
        $table->where($map)->field($field);
        if ($input['priceOrder']) $table->order('a.price', $input['priceOrder']);
        if ($input['salesOrder']) $table->order('a.sales', $input['salesOrder']);
        try {
            $data = $table->page($input['page'], 10)->selectOrFail()->toArray();
            return jsonSuccess('获取成功', $data);
        } catch (E $e) {
            return jsonFail('未找到数据');
        }
    }

    /**商品详情
     * @param array $input
     * @return Json
     */
    public static function detail($input)
    {
        try {
            $field = 'a.sales,a.info,a.center_id,a.create_time,a.cate_id,a.description,a.id,a.image,';
            $field .= 'a.status,a.is_hot,a.ot_price,a.price,a.act_price,is_activity,a.sort,a.stock,a.name,a.sales,';
            $field .= 'b.name as unit_name,c.name as cate_name,d.area,sum(ca.num) as cate_num';
            $storeInfo = Db::table(self::$_table)->alias('a')
                ->join('goods_unit b', 'a.unit_id = b.id')
                ->join('category c', 'a.cate_id = c.id')
                ->join('organization d', 'a.center_id = d.id')
                ->leftjoin('cart ca','ca.goods_id = a.id')
                ->where('ca.group_id', $input['group_id'])
                ->where('a.id', $input['goods_id'])->field($field)->find();
            if (empty($storeInfo)) return jsonFail('暂无商品');
            //替换windows服务器下正反斜杠问题导致图片无法显示
            $storeInfo['description'] = preg_replace_callback('#<img.*?src="([^"]*)"[^>]*>#i', function ($imagsSrc) {
                return isset($imagsSrc[1]) && isset($imagsSrc[0]) ? str_replace($imagsSrc[1], str_replace('\\', '/', $imagsSrc[1]), $imagsSrc[0]) : '';
            }, $storeInfo['description']);
            $data['productInfo'] = $storeInfo;
            $data['productReply'] = self::getProductAttrReply($input['goods_id'], $input['admin_id']);
            return jsonSuccess('获取成功', $data);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**
     * 获取商品属性数据
     * @param $productId
     * @return array
     */
    public static function getProductAttrReply($productId, $admin_id)
    {
        $field = 'a.goods_score,a.service_score,a.comment,a.pics,a.merchant_reply_content,a.merchant_reply_time,a.add_time,b.username,b.portrait';
        $reply = Db::table(self::$goods_reply)->alias('a')->join('user b', 'a.uid = b.id')->where('a.status', 1)->where('a.goods_id', $productId)->field($field)->select()->toArray() ?: [];
        return $reply;
    }

    /**
     * 获取商品日志
     * @param $productId
     * @return json
     */
    public static function goodsLogs($input)
    {
        if (in_array($input['type'], [1, 2, 3])) {
            $data = Db::table(self::$goods_log)->alias('a')
                ->join('goods b', 'a.goods_id=b.id')
                ->join('goods_unit c', 'b.unit_id=c.id')
                ->where('a.goods_id', $input['goods_id'])
                ->where('a.type', $input['type'])
                ->field('a.*,b.name as goods_name,c.name as unit_name')
                ->select()->toArray();
        } else {
            $data = Db::table('purchase')->alias('a')
                ->join('goods b', 'a.goods_id=b.id')
                ->join('goods_unit c', 'b.unit_id=c.id')
                ->where('a.goods_id', $input['goods_id'])
                ->where('a.status', 1)
                ->field('a.*,b.name as goods_name,c.name as unit_name')
                ->select()->toArray();
        }
        return jsonSuccess('获取成功', $data);
    }
}